package br.com.ericogr.hanoi.tarefa;

import android.util.Log;

public abstract class TarefaBase implements Tarefa {
    private Thread mThread;
    private boolean mLiberada;
    private boolean mExecutando;
    
    private String mNome;
    private long mAtraso;
    
    public TarefaBase(String nome) {
        this(nome, 0);
    }
    
    public TarefaBase(String nome, long atraso) {
        mNome = nome;
        mAtraso = atraso;
    }
    
    private void processar() {
        long sleepTime;
        long beforeTime;
        
        while (mLiberada) {
            beforeTime = System.nanoTime();
            
            executar();

            if (mAtraso > 0) {
                sleepTime = mAtraso - ((System.nanoTime() - beforeTime) / 1000000L);
                
                try {
                    if (sleepTime > 0) {
                        Thread.sleep(sleepTime);
                    }
                } catch (InterruptedException ex) {
                    Log.i(this.getClass().getName(), null, ex);
                }
            }
        }
        
        mExecutando = false;
    }
    
    private void iniciarTarefa() {
        mThread = new Thread(new Runnable() {
            public void run() {
                processar();
            }
        }, "Tarefa " + mNome);
        
        mThread.start();
    }
    
    @Override
    public void iniciar() {
        mLiberada = true;
        mExecutando = true;

        iniciarTarefa();
    }
    
    @Override
    public void parar() {
        mLiberada = false;
    }
    
    @Override
    public final boolean isExecutando() {
        return mExecutando;
    }
}
